package com.ssyc.student.activity;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.OneKeyShareCallback;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.manager.ShareManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.student.R;
import com.ssyc.student.adapter.StCardGvAdapter;
import com.ssyc.student.bean.LessonInfo;
import com.ssyc.student.bean.PunchCardInfo;
import com.ssyc.student.bean.ResultInfo;
import com.ssyc.student.bean.ShareLessonInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import okhttp3.Call;

/**
 * 学生端--打卡记录界面
 * Created by Administrator on 2018/4/24 0024.
 */

@Route(path = "/student/StudentPunchCardActivity")
public class StudentPunchCardActivity extends BaseActivity implements View.OnClickListener {

    //加载框
    private RelativeLayout rlLoadingView;

    //内容布局
    private LinearLayout llContent;

    private ImageView ivBack;
    //累计打卡次数
    private TextView tvCardNum;
    //掌握单词个数
    private TextView tvZwdc;
    //掌握单词对应的课程Lesson
    private TextView tvZwdcLesson;
    //学习时长
    private TextView tvXxsc;
    //学习时长对应的课程Lesson
    private TextView tvXxscLesson;
    //累计掌握单词个数
    private TextView tvLjzw;
    //累计学习时长
    private TextView tvLjxxsc;
    //展示详情的列表
    private GridView gv;

    //空视图
    private RelativeLayout emptyView;

    //数据集合
    private List<PunchCardInfo.DataBean.LessonStateBean> oldDatas;

    //适配器
    private StCardGvAdapter adapter;

    //请求的账号
    private String acc;

    //请求的token
    private String apptoken;
    private TextView tvMsg;


    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return "";
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_punch_card;
    }

    @Override
    protected void init() {
        showContent();

        //初始化控件
        initView();

        //获取Intent
        initIntent();

        //获取数据
        http();
    }


    /**
     * 初始化控件
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        tvCardNum = findViewById(R.id.tv_card_num);
        tvZwdc = findViewById(R.id.tv_zwdc);
        tvZwdcLesson = findViewById(R.id.tv_zwdc_lesson);
        tvXxsc = findViewById(R.id.tv_xxsc);
        tvXxscLesson = findViewById(R.id.tv_xxsc_lesson);
        tvLjzw = findViewById(R.id.tv_ljzw);
        tvLjxxsc = findViewById(R.id.tv_ljxxsc);
        gv = findViewById(R.id.gv);
        rlLoadingView = findViewById(R.id.rl_loading);
        rlLoadingView.setVisibility(View.VISIBLE);
        llContent = findViewById(R.id.ll_content);
        llContent.setVisibility(View.GONE);
        emptyView = findViewById(R.id.rl_empty);
        tvMsg = findViewById(R.id.tv_content);
        tvMsg.setText("暂无打卡记录");
        emptyView.setVisibility(View.GONE);
    }

    /**
     * 获取Intent数据
     */
    private void initIntent() {
        String account = getIntent().getStringExtra("acc");
        if (TextUtils.isEmpty(account)) {
            acc = AccountUtils.getAccount(this);
        } else {
            //教师端--排行榜--打卡--查看记录界面跳转过来的
            acc = account;
        }
        apptoken = AccountUtils.getToken(this);
    }


    /**
     * 获取页面数据
     */
    private void http() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "25");
        map.put("acc", acc);
        map.put("role", "0");
        map.put("apptoken", apptoken);
        map.put("platform", "8");
        Log.i("test", "apptoken=" + apptoken + "&platform=8");

        HttpUtils.post(HttpAdress.PUNCHCARD, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoadingView) {
                    rlLoadingView.setVisibility(View.GONE);
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                if (null != rlLoadingView) {
                    rlLoadingView.setVisibility(View.GONE);
                }
                if (!TextUtils.isEmpty(response)) {

                    PunchCardInfo info = null;

                    try {
                        info = GsonUtil.jsonToBean(response, PunchCardInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }


                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            PunchCardInfo.DataBean data = info.getData();
                            if (null != data) {


                                //设置掌握单词,学习时长,累计掌握单词,累计学习时长
                                setWordsAndTimes(true, data.getLesson_word(), data.getLesson_time(), data.getAll_word(), data.getAll_time(), data.getLesson_last(), data.getFrequency());

                                //设置列表的数据
                                oldDatas = data.getLesson_state();
                                if (oldDatas == null || oldDatas.size() == 0) {
                                    //证明没有打卡数据
                                    emptyView.setVisibility(View.VISIBLE);
                                    llContent.setVisibility(View.GONE);
                                } else {
                                    emptyView.setVisibility(View.GONE);
                                    llContent.setVisibility(View.VISIBLE);
                                    //设置列表
                                    initGv();
                                }
                            }
                        } else {
                            //服务器返回异常状态码
                            UiUtils.Toast("返回异常码是:" + info.getState(), false);
                            Log.i("test", "返回异常码是:" + info.getState());
                        }
                    }
                }
            }
        });
    }

    /**
     * 设置掌握单词数,学习时长,累计掌握单词,累计学习时长,展示的单元名称
     *
     * @param lesson_word 掌握单词
     * @param lesson_time 学习时长
     * @param all_word    累计掌握单词
     * @param all_time    累计掌握时长
     * @param lesson_last 课程名称
     * @param frequency   累计打卡次数
     */
    private void setWordsAndTimes(boolean flag, String lesson_word, String lesson_time, String all_word, String all_time, String lesson_last, String frequency) {
        //掌握单词
        if (TextUtils.isEmpty(lesson_word)) {
            tvZwdc.setText("0");
        } else {
            tvZwdc.setText(lesson_word);
        }

        //课程名称
        if ("0".equals(lesson_last)) {
            tvZwdcLesson.setText("Lesson1");
            tvXxscLesson.setText("Lesson1");
        } else {
            tvZwdcLesson.setText("Lesson " + lesson_last);
            tvXxscLesson.setText("Lesson " + lesson_last);
        }


        //学习时长,这里返回的是秒
        if (TextUtils.isEmpty(lesson_time)) {
            tvXxsc.setText("0");
        } else {
            tvXxsc.setText((Integer.parseInt(lesson_time) / 60) + "");
        }

        if (flag) {
            //累计掌握单词
            if (TextUtils.isEmpty(all_word)) {
                tvLjzw.setText("0");
            } else {
                tvLjzw.setText(all_word);
            }

            //累计学习时长返回的是秒需要转换
            if (TextUtils.isEmpty(all_time)) {
                tvLjxxsc.setText("0");
            } else {
                tvLjxxsc.setText((Integer.parseInt(all_time) / 60) + "");
            }

            //累计打卡次数
            if (TextUtils.isEmpty(frequency)) {
                tvCardNum.setText("0");
            } else {
                tvCardNum.setText(frequency);
            }

        }
    }

    /**
     * 设置GridView的方法
     */
    private void initGv() {

        adapter = new StCardGvAdapter(this, oldDatas, R.layout.st_gv_item_lesson, new StCardGvAdapter.PrepareAndReviewClickListener() {
            @Override
            public void onPrepaerClick(int pos) {
                doHttpLessonInfo(1, pos);
            }

            @Override
            public void onReviewClick(int pos) {
                doHttpLessonInfo(2, pos);
            }
        });

        gv.setAdapter(adapter);
    }

    /**
     * @param type 1表示预习  2表示复习
     *             点击预习请求当前Lesson的所有数据信息,进行顶部页面刷新操作
     */
    private void doHttpLessonInfo(int type, int pos) {

        //如果是灰色的表示学习完可打卡,点击调用第三方分享,分享回调成功后请求服务器接口同步状态
        //如果是白色表示没学习也不可打卡
        //如果是绿色表示学习了已经打卡,直接请求服务器接口刷新数据即可
        if (type == 1) {
            //预习
            String preview = oldDatas.get(pos).getPreview();
            if ("1".equals(preview)) {
                //学习未打卡,灰色背景,调用分享的方法
                doGetLessonDetailsAction(type, pos);
                if ("0".equals(AccountUtils.getRole(StudentPunchCardActivity.this))) {

                    //获取分享信息
                    getStudyInfo(type, pos, true);
                }
            } else if ("2".equals(preview)) {
                //学习已经打卡,点击时只更新顶部的Lesson的内容
                doGetLessonDetailsAction(type, pos);
                if ("0".equals(AccountUtils.getRole(StudentPunchCardActivity.this))) {

                    //获取分享信息
                    getStudyInfo(type, pos, false);
                }
            }

        } else if (type == 2) {
            //复习
            String review = oldDatas.get(pos).getReview();
            if ("1".equals(review)) {
                //学习未打卡,灰色背景,调用分享的方法
                doGetLessonDetailsAction(type, pos);

                if ("0".equals(AccountUtils.getRole(StudentPunchCardActivity.this))) {
                    //获取分享信息
                    getStudyInfo(type, pos, true);
                }
            } else if ("2".equals(review)) {
                //学习已经打卡,点击时更新顶部的Lesson的内容
                doGetLessonDetailsAction(type, pos);

                if ("0".equals(AccountUtils.getRole(StudentPunchCardActivity.this))) {

                    //获取分享信息
                    getStudyInfo(type, pos, false);
                }
            }
        }
    }

    /**
     * 获取分享当前Lesson对应的详细数据的方法a
     */
    private void getStudyInfo(int type, int pos, boolean isCard) {

        //请求服务器
        Map<String, String> map = new HashMap<>();
        map.put("type", "34");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", "0");
        map.put("lessonId", (pos + 1) + "");
        map.put("module", (type - 1) + "");
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.SHARELESSON, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast(BaseApplication.ERROR, false);
                PopUpManager.dismiss();
            }

            @Override
            public void onResponse(String response, int id) {

                PopUpManager.dismiss();

                if (!TextUtils.isEmpty(response)) {
                    ShareLessonInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ShareLessonInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }

                    Log.i("test", "单元：" + response);
                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            ShareLessonInfo.DataBean data = info.getData();
                            if (null != data) {
                                //分享掌握单词,学习时长,累计掌握单词,累计学习时长
                                doShareAction(type, pos, data.getStu_word(),
                                        data.getStu_text(), data.getStu_time(), isCard);
                            }

                        } else {
                            //服务器返回异常状态码
                            UiUtils.Toast("返回异常码是:" + info.getState(), false);
                            Log.i("test", "返回异常码是:" + info.getState());
                        }
                    }
                }

            }
        });

    }


    /**
     * 获取当前Lesson对应的详细数据的方法a
     *
     * @param pos
     */
    private void doGetLessonDetailsAction(int type, int pos) {
        //请求服务器获取当前Lesson的相信信息的方法
        PopUpManager.showPop(this, R.layout.base_small_loading, 1.0f, this, null);
        //请求服务器
        Map<String, String> map = new HashMap<>();
        map.put("type", "26");
        map.put("acc", acc);
        map.put("role", "0");
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "8");
        map.put("lesson", (pos + 1) + "");

        HttpUtils.post(HttpAdress.PUNCHCARD, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast(BaseApplication.ERROR, false);
                PopUpManager.dismiss();
            }

            @Override
            public void onResponse(String response, int id) {

                PopUpManager.dismiss();

                if (!TextUtils.isEmpty(response)) {
                    LessonInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, LessonInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }

                    Log.i("test", "单元：" + response);
                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            LessonInfo.DataBean data = info.getData();
                            if (null != data) {
                                //设置掌握单词,学习时长,累计掌握单词,累计学习时长
                                setWordsAndTimes(false, data.getWork_num(),
                                        data.getStudy_time() + "",
                                        data.getWork_num(),
                                        data.getStudy_time() + "", data.getLesson_id(),
                                        "");


                            }

                        } else {
                            //服务器返回异常状态码
                            UiUtils.Toast("返回异常码是:" + info.getState(), false);
                            Log.i("test", "返回异常码是:" + info.getState());
                        }
                    }
                }

            }
        });
    }


    /**
     * 分享的方法
     */
    private void doShareAction(int type, int pos, String count, String learn,
                               String times, boolean isCard) {


        //新地址
        String shareUrl = HttpAdress.UPDATE_URL + "JPXB/sharePage/pages/JPXB/new_2_sharing_interface/share_revise_preparation.html?" +
                "acc=" + AccountUtils.getAccount(this) +
                "&role=" + AccountUtils.getRole(this) +
                "&lessonId=" + (pos + 1) + "&module=" + (type - 1);


        //图标
//        String imgUrl = "http://139.129.57.83:8080/Appandroid/jpxblogo.png";
        String imgUrl = "https://www.ycsjedu.com/share/Appandroid/jpxblogo.png";


        //分享标题
        String title = AccountUtils.getName(this) + "同学在金牌学霸" + "lesson" + (pos + 1) +
                getType(type) + "了" + count + "个单词，" + learn + "篇课文,该课学习了" + times + "分钟";

        ShareManager.newInstance().showOneShare(this, title, shareUrl, "分享内容", imgUrl, shareUrl, new OneKeyShareCallback() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Log.i("test", "分享成功");

                //是否回调
                if (isCard) {
                    //分享成功后调用本地的接口,同步页面的状态
                    httpSyncState(type, pos);
                }
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Log.i("test", "分享失败");
            }

            @Override
            public void onCancel(Platform platform, int i) {

                Log.i("test", "取消分享");
            }
        });
    }

    /**
     * 判断预习复习
     */
    private String getType(int type) {
        String TYPE = "学习";
        if (type == 1) {
            //预习
            TYPE = "预习";
        } else if (type == 2) {
            TYPE = "复习";
        }
        return TYPE;
    }


    /**
     * 分享成功后请求本地接口通过不状态的方法
     *
     * @param type
     * @param pos
     */
    private void httpSyncState(int type, int pos) {

        Map<String, String> map = new HashMap<>();
        map.put("type", "30");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        if (type == 1) {
            map.put("module", "0");
        } else if (type == 2) {
            map.put("module", "1");
        }
        map.put("lessonId", (pos + 1) + "");
        map.put("apptoken", AccountUtils.getToken(this));

        HttpUtils.post(HttpAdress.PUSHCARD, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                ResultInfo info = null;
                if (!TextUtils.isEmpty(response)) {
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }

                    if (info != null) {
                        if ("200".equals(info.state)) {
                            if (type == 1) {
                                oldDatas.get(pos).setPreview("2");
                            } else if (type == 2) {
                                oldDatas.get(pos).setReview("2");
                            }
                            adapter.notifyDataSetChanged();

                            String count = (Integer.parseInt(tvCardNum.getText().toString()) + 1) + "";

                            tvCardNum.setText(count);
                            //打卡分享成功
                            UiUtils.Toast("打卡分享成功", false);
                        } else {
                            UiUtils.Toast("删除失败,错误码是:" + info.state, false);
                            Log.i("test", "错误码是:" + info.state);
                        }
                    }
                }
            }
        });
    }


    /**
     * 页面控件的点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        }
    }
}
